<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50 px-4">
    <n-card class="w-full max-w-5xl py-12">
      <div class="flex justify-between items-center mb-6">
        <span class="text-2xl font-bold text-blue-600">用户管理</span>
        <n-button type="primary" @click="showAddModal = true">新增用户</n-button>
      </div>
      <n-data-table :columns="columns" :data="users" :pagination="pagination" />
      <!-- 新增/编辑用户弹窗 -->
      <n-modal v-model:show="showAddModal">
        <n-card style="width: 400px">
          <n-form :model="form" class="flex flex-col gap-4">
            <n-form-item label="用户名">
              <n-input v-model:value="form.userName" placeholder="请输入用户名" />
            </n-form-item>
            <n-form-item label="手机号">
              <n-input v-model:value="form.phone" placeholder="请输入手机号" />
            </n-form-item>
            <n-form-item label="密码" v-if="!form.uid">
              <n-input v-model:value="form.password" type="password" placeholder="请输入密码" />
            </n-form-item>
            <n-form-item>
              <n-button type="primary" @click="handleSave" block>保存</n-button>
            </n-form-item>
          </n-form>
        </n-card>
      </n-modal>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, h, onMounted } from 'vue';
import { fetchUserList, addUser, updateUser, deleteUser } from '../api/user';

const users = ref<any[]>([]);
const showAddModal = ref(false);
const form = ref<any>({});

const columns = [
  { title: 'UID', key: 'uid' },
  { title: '用户名', key: 'userName' },
  { title: '手机号', key: 'phone' },
  { title: '创建时间', key: 'created_at' },
  {
    title: '操作',
    key: 'actions',
    render(row: any) {
      return [
        h('n-button', { size: 'small', onClick: () => editUser(row) }, '编辑'),
        h('n-popconfirm', { onPositiveClick: () => handleDelete(row.uid) }, {
          default: () => '确定删除？',
          trigger: () => h('n-button', { size: 'small', type: 'error' }, '删除')
        })
      ];
    }
  }
];

const pagination = { pageSize: 10 };

const loadUsers = async () => {
  const res = await fetchUserList();
  users.value = res.data || [];
};

function editUser(row: any) {
  form.value = { ...row, password: '' };
  showAddModal.value = true;
}

async function handleSave() {
  if (form.value.uid) {
    await updateUser(form.value);
  } else {
    await addUser(form.value);
  }
  showAddModal.value = false;
  form.value = {};
  loadUsers();
}

async function handleDelete(uid: string) {
  await deleteUser(uid);
  loadUsers();
}

onMounted(loadUsers);
</script> 